package top.yangbuyi.acpect;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.yangbuyi.acpect.annotaction.ULogAnnotation;

import java.lang.reflect.Method;


/**
 * @description: 杨不易网站:www.yangbuyi.top
 * @program: yangbuyiopenHis2020
 * @ClassName: methodTitleApect
 * @create: 2020-08-28 10:36
 * @author: yangbuyi
 * @since： JDK1.8
 * @methodTitleApect: 用于切面方法上上面的操作日志注解处理$
 **/

@Aspect
@Component
@Slf4j
@Order(2)
public class MethodTitleAspect {

	  /**
	   * 此处的切点是注解的方式
	   * 只要出现 @ULogAnnotation注解都会进入
	   */
	  @Pointcut("@annotation(top.yangbuyi.acpect.annotaction.ULogAnnotation)")
	  public void logPointCut() {

	  }

	  /**
	   * 环绕增强,相当于MethodInterceptor
	   *
	   * @param point
	   * @return
	   * @throws Throwable
	   */
	  @Around("logPointCut()")
	  public Object around(ProceedingJoinPoint point) throws Throwable {
			long beginTime = System.currentTimeMillis();
			//执行方法
			Object result = point.proceed();

			//保存日志
			try {
				  saveSysLog(point, beginTime);
			} catch (Exception e) {
				  log.error("e={}", e);
			}

			return result;
	  }

	  /**
	   * 把日志保存
	   */
	  private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
			MethodSignature signature = (MethodSignature) joinPoint.getSignature();
			Method method = signature.getMethod();

			// 拿到方法字节码
			ULogAnnotation logAnnotation = method.getAnnotation(ULogAnnotation.class);
			if (logAnnotation != null) {
				  //注解上的描述
				  log.info("描述:" + logAnnotation.title() + "--------" + logAnnotation.action());
			}

			//请求的方法名
			String className = joinPoint.getTarget().getClass().getName();
			String methodName = signature.getName();

			try {
				  //请求的参数
				  Object[] args = joinPoint.getArgs();
				  String params = null;
				  if (args.length != 0) {
						params = JSONUtil.toJsonStr(args);
				  }
				  //执行时长(毫秒)
				  time = System.currentTimeMillis() - time;
				  log.info("请求的参数:{}" + params);
				  log.info("访问路径:" + className);
				  log.info("方法名称:" + methodName);
				  log.info("耗时毫秒:" + (time));
				  // 保存日志信息
			} catch (Exception e) {

			}

	  }

}